<?php

namespace app\api\model;

use app\common\enums\StatusEnum;

class LangClassLessonRecite extends \app\common\model\LangClassLessonRecite
{
    /**
     * 获取每节课下面所有的单词或者句子 和 答案
     * @param $oauthId
     * @param $lessonId
     * @param $type
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getListByLesson($oauthId, $lessonId, $type)
    {
        // 查找班级对应的所有单词或者句子
        $sql = static::field('id AS reciteId, class_id AS classId, word')
            ->where(['lesson_id' => $lessonId, 'type' => $type, 'status' => StatusEnum::ENABLED]);

        $recite = $sql->order(['sort_num' => 'desc', 'create_time' => 'desc'])
            ->select()
            ->toArray();

        if (empty($recite)) {
            return [
                'noData' => true,
                'isBuy' => false,
                'list' => [],
                'count' => 0,
            ];
        }

        $classId = $recite[0]['classId'];
        // 判断是否已经购买
        $one = OauthOrderClass::getOneByClass($oauthId, $classId);
        if (empty($one)) {
            return [
                'isBuy' => false,
                'list' => [],
                'count' => 0
            ];
        }

        $reciteIds = [];
        foreach ($recite as $key => $value) {
            $reciteIds[$value['reciteId']] = $value['reciteId'];
        }

        // 单词或句子对应的答案
        if ($reciteIds) {
            $answers = LangClassLessonReciteAnswer::getListByRecite($reciteIds);
            foreach ($recite as $key => $value) {
                $recite[$key]['answers'] = isset($answers[$value['reciteId']]) ? $answers[$value['reciteId']] : [];
            }
        }

        return [
            'isBuy' => true,
            'list' => $recite,
            'count' => $sql->count()
        ];
    }

    /**
     * 通过ID找数据
     * @param $ids
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getByIds($ids)
    {
        return static::field('id AS reciteId, class_id AS classId')
            ->where('id', 'in', $ids)
            ->where(['status' => StatusEnum::ENABLED])
            ->select()
            ->column('classId', 'reciteId');
    }
}